import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:hayll_app_village_master/hayll/network/yll_request_bean.dart';
import 'package:hayll_app_village_master/hayll/network/yll_response_bean.dart';
import 'package:json_annotation/json_annotation.dart';

import 'base.dart';

class YllNetwork {
  static var _requestBean = YllRequestBean();
  static var _requestingMap = Map<int, String>();

  static void setLoginCache(String token, int userId, String phone) {
    if (_requestBean.head == null) {
      _createRequestEntity();
    }
    _requestBean.head.token = token;
    _requestBean.head.bizId = userId.toString();
    _requestBean.head.phone = phone;
  }

  static void _createRequestEntity() {
    _requestBean.head = YllRequestHead();
    _requestBean.head.appVersion = '1.0.0';
    _requestBean.head.callType = 'flutter';
    _requestBean.head.clientId = '123ae121';
    _requestBean.head.systemVersion = '1.0.1';
    _requestBean.head.protocolVersion = '1.0.0';
  }

  static void requestPost(String path,
      {Map<String, dynamic> params,
      void Function(Map<String, dynamic>) success,
      void Function(int, String) failed}) async {
    //封装params
    if (_requestBean.head == null) {
      _createRequestEntity();
    }
    var time = DateTime.now().millisecondsSinceEpoch;

    _requestBean.head.sequenceCode = '$time';
    _requestBean.head.requestTime = '$time';
    _requestBean.body = params;
    _requestBean.sign = 'hayll2017';

    var allJson = jsonEncode(_requestBean.toJson());
    var sign = md5.convert(Utf8Encoder().convert(allJson));
    _requestBean.sign = sign.toString();

    _requestingMap[time] = path;
    print('请求数据:${_requestBean.toJson()}');
    AbsNetwork.post(path, params: _requestBean.toJson(), success: (json) {
      print('返回数据:$json');
      try {
        var bean = YllResponseBean.fromJson(json);
        if (bean.head != null) {
          if (bean.head.status == '0') {
            //success
            //如果请求事件是登录事件，拦截返回体的token信息
            var key = int.parse(bean.head.sequenceCode);
            if (_requestingMap.containsKey(key)) {
              var method = _requestingMap.remove(key);
            }
            if (bean.body is Map) {
              try{
                success(bean.body);
              }catch(e){
                print(e.toString());
              }
            } else if (bean.body is List) {
              success({'data': bean.body});
            } else {
              failed(-103, '数据解析异常');
            }
          } else {
            failed(int.parse(bean.head.status), bean.head.errorMessage);
          }
        } else {
          failed(-101, '数据解析异常');
        }
      } catch (e) {
        failed(-102, '数据解析异常${e.toString()}');
      }
    }, failed: failed);
  }
}
